<template>
    <div class="forum-container">
        <div class="welcome-banner glassmorphism">
  <h1>欢迎来到高校二手交易平台论坛！</h1>
  <p class="subtitle">在这里分享你的校园生活，交流交易心得</p>
</div>
      <!-- 用户信息及创建按钮 -->
      <div class="user-header glassmorphism">
        <div v-if="userInfo" class="user-info">
          <div class="avatar-box">
            <img :src="'http://localhost:8092' + userInfo.avatar" class="user-avatar" alt="用户头像" />
          </div>
          <div class="user-meta">
            <h2 class="welcome-text">欢迎回来，{{ userInfo.nickname }} 👋</h2>
            <p class="user-credit">信用积分：{{ userInfo.credit }}</p>
          </div>
          <el-button 
            type="primary" 
            @click="showCreateDialog"
            class="create-btn gradient-btn"
          >
            <el-icon><Plus /></el-icon> 新建话题
          </el-button>
        </div>
      </div>
  
      <!-- 创建话题对话框 -->
      <el-dialog
        v-model="createDialogVisible"
        title="创建新话题"
        width="600px"
        class="modern-dialog"
      >
        <el-form 
          :model="newTopic" 
          ref="topicForm" 
          :rules="formRules"
          label-position="top"
        >
          <el-form-item label="分享你的想法" prop="topic">
            <el-input
              v-model="newTopic.topic"
              type="textarea"
              :rows="4"
              placeholder="请输入话题内容（最多200字）"
              maxlength="200"
              show-word-limit
              class="modern-input"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="createDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button 
            type="primary"
            @click="submitTopic"
            :loading="submitting"
            class="confirm-btn"
          >
            立即发布
          </el-button>
        </template>
      </el-dialog>
  
      <!-- 话题列表 -->
      <div class="topic-list">
        <transition-group name="staggered-fade" tag="div" class="grid-container">
          <div 
            class="topic-card glassmorphism"
            v-for="topic in topics" 
            :key="topic.topicId"
            @click="handleTopicClick(topic.topicId)"
          >
            <div class="card-header">
              <img :src="'http://localhost:8092' + topic.avatar" class="author-avatar" alt="用户头像" />
              <div class="author-info">
                <span class="author-name">{{ topic.nickname }}</span>
                <span class="post-time">{{ formatDate(topic.createdAt) }}</span>
              </div>
            </div>
            <div class="card-content">
              <h3 class="topic-title">{{ topic.topic }}</h3>
            </div>
            <div class="interaction-bar">
             <div class="interaction-item">
              <el-icon><View /></el-icon> <!-- 新增浏览图标 -->
              <span>{{ topic.view || 0 }}</span> <!-- 展示真实浏览量 -->
            </div>
             <div class="interaction-item">
    <el-icon><ChatDotRound /></el-icon>
    <span>{{ topic.commentCount || 0 }}</span>
  </div>
            </div>
          </div>
        </transition-group>
      </div>
    </div>
  </template>
  
  <script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRoute ,useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ChatDotRound, Star ,View} from '@element-plus/icons-vue'
  
  const route = useRoute()
  const userInfo = ref(null)
  const userId = ref(null)
  const topics = ref([])
  const router = useRouter()
  // 创建话题相关状态
  const createDialogVisible = ref(false)
  const submitting = ref(false)
  const newTopic = ref({ topic: '' })
  const topicForm = ref(null)
  
  // 表单验证规则
  const formRules = {
    topic: [
      { required: true, message: '请输入话题内容', trigger: 'blur' },
      { max: 200, message: '内容长度不能超过200字', trigger: 'blur' }
    ]
  }
  
  // 日期格式化
  const formatDate = (date) => {
    return new Date(date).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  // 获取用户信息
  const fetchUserDetail = async (userId) => {
    try {
      const { data } = await axios.get(`http://localhost:8092/user/getUserDetailById`, {
        params: { userId }
      })
      if (data?.code === 200) {
        userInfo.value = Array.isArray(data.data) && data.data.length > 0 ? data.data[0] : {};
      }
    } catch (error) {
      console.error("用户信息加载失败", error)
    }
  }
  
  // 获取话题列表
  const fetchTopics = async () => {
    try {
      const { data } = await axios.get("http://localhost:8092/topic/list")
      if (data.code === 200) {
         topics.value = data.data.filter(topic => 
        topic.approvalStatus === 1
      )
      }
    } catch (error) {
      console.error("获取话题失败:", error)
    }
  }
  
  // 显示创建对话框
  const showCreateDialog = () => {
    if (!userInfo.value?.userId) {
      ElMessage.warning('请先登录')
      return
    }
    createDialogVisible.value = true
  }
  
  // 提交话题
  const submitTopic = async () => {
    try {
      // 表单验证
      const valid = await topicForm.value.validate()
      if (!valid) return
  
      submitting.value = true
      
      // 构造请求数据
      const postData = {
        topic: newTopic.value.topic,
        userId: userInfo.value.userId,
        nickname: userInfo.value.nickname,
        avatar: userInfo.value.avatar
      }
  
      const { data } = await axios.post(
        'http://localhost:8092/topic/create',
        postData
      )
  
      if (data.code === 200) {
        ElMessage.success('话题创建成功')
        createDialogVisible.value = false
        newTopic.value.topic = ''
        await fetchTopics()
      } else {
        ElMessage.error(data.msg || '创建失败')
      }
    } catch (error) {
      console.error('创建失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    } finally {
      submitting.value = false
    }
  }
  
  // 点击话题处理
 const handleTopicClick = async (topicId) => {
  try {
    // 调用新增的浏览量接口
    await axios.post('http://localhost:8092/topic/incrementView', {
      topicId: topicId
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
  } catch (error) {
    console.error('浏览量更新失败:', error);
  }
  
  // 保持原有的跳转逻辑
  const routeData = router.resolve({
    path:'/forumsdetail',
    query: {
      topicId: topicId,
      userId: userId.value
    }
  })
  window.open(routeData.href, '_blank')
}
  
  // 初始化加载
  onMounted(async () => {
    userId.value = route.query.userId
    if (userId.value) {
      await fetchUserDetail(userId.value)
      await fetchTopics()
    }
  })
  </script>
  
  <style scoped>
  .welcome-banner {
  text-align: center;
  padding: 2rem;
  margin-bottom: 2rem;
  background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
  color: black;
  
  h1 {
    font-size: 2rem;
    margin: 0 0 0.5rem;
    font-weight: 600;
    letter-spacing: 1px;
  }
  
  .subtitle {
    margin: 0;
    opacity: 0.9;
    font-size: 1.1rem;
  }
}
/* 基础样式重置 */
.forum-container {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

/* 玻璃拟态效果 */
.glassmorphism {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* 用户头部 */
.user-header {
  padding: 1.5rem;
  margin-bottom: 1.5rem; /* 原为2rem */
  transition: all 0.3s ease;

  .user-info {
    display: flex;
    align-items: center;
    gap: 1.5rem;

    .avatar-box {
      position: relative;
      width: 64px;
      height: 64px;
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

      .user-avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .user-meta {
      flex: 1;

      .welcome-text {
        margin: 0;
        font-size: 1.5rem;
        color: #2c3e50;
        font-weight: 600;
      }

      .user-credit {
        margin: 0.5rem 0 0;
        color: #7f8c8d;
        font-size: 0.9rem;
      }
    }
  }
}

/* 渐变按钮 */
.gradient-btn {
  background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
  border: none;
  padding: 0.75rem 1.5rem;
  font-weight: 500;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(99, 102, 241, 0.3);
  }
}

/* 话题列表 */
.topic-list {
  .grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 1.5rem;
  }
}

/* 话题卡片 */
.topic-card {
  padding: 1.5rem;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 1rem;

    .author-avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      margin-right: 1rem;
      object-fit: cover;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .author-info {
      .author-name {
        font-weight: 600;
        color: #2c3e50;
      }

      .post-time {
        font-size: 0.85rem;
        color: #7f8c8d;
      }
    }
  }

  .topic-title {
    margin: 0;
    color: #34495e;
    font-size: 1.1rem;
    line-height: 1.6;
    font-weight: 500;
  }

  .interaction-bar {
    display: flex;
    gap: 1.5rem;
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #eee;

    .interaction-item {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      color: #7f8c8d;
      font-size: 0.9rem;

      .el-icon {
        font-size: 1.1rem;
      }
    }
  }
}

/* 现代对话框 */
.modern-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #eee;
    margin-bottom: 1.5rem;

    .el-dialog__title {
      font-size: 1.25rem;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .modern-input {
    .el-textarea__inner {
      border-radius: 8px;
      padding: 1rem;
      font-size: 1rem;
      transition: all 0.3s ease;

      &:focus {
        border-color: #6366f1;
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }
    }
  }

  .confirm-btn {
    background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
    border: none;
    padding: 0.75rem 2rem;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(99, 102, 241, 0.3);
    }
  }

  .cancel-btn {
    border-color: #eee;
    color: #7f8c8d;

    &:hover {
      color: #6366f1;
      border-color: rgba(99, 102, 241, 0.3);
    }
  }
}

/* 入场动画 */
.staggered-fade-move,
.staggered-fade-enter-active,
.staggered-fade-leave-active {
  transition: all 0.5s ease;
}

.staggered-fade-enter-from,
.staggered-fade-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.staggered-fade-leave-active {
  position: absolute;
}
</style>